{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.stock-body tr:first-child:hover td{background-color:#fff}
	.stock-body,.stock-body tr,.stock-body tr td{background-color:#fff}
	.stock-view{padding:20px}
	.stock-search-block{position:relative}
	.stock-autocomplete-list{position:absolute;z-index:9999;background-color:#fff;width:500px;box-shadow:0 3px 6px -4px rgba(0,0,0,.12),0 6px 16px 0 rgba(0,0,0,.08),0 9px 28px 8px rgba(0,0,0,.05);border-radius:4px;overflow:hidden;color:rgba(0,0,0,.85);font-variant:tabular-nums;line-height:1.5715;list-style:none;left:0;top:62px;display:none}
	.stock-autocomplete-list ul{padding:6px 0}
	.stock-autocomplete-list ul li{font-weight:400;font-size:14px;text-align:left;padding:5px 12px;color:rgba(0,0,0,.85)}
	.stock-li-hover{background-color:#f5f5f5}
	.stock-sku-no{display:inline-block;float:right}
	.ns-title-pic{width:45px;height:45px;text-align:center}
	.table-goods-info{display:flex;flex-direction:column;width:calc(100% - 90px);margin-left:15px}
	.table-goods-info>div{width:100%}
	.table-goods-info *{line-height:1.5}
	.table-goods-info .goods-name{width:100%;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;white-space:break-spaces;line-height:1.3}
	.ns-table-title{display:flex;align-items:center}
	.ns-title-pic img{display:inline-block;height:auto;width:auto;max-height:100%;max-width:100%}
	.ns-table-title .ns-title-content{display:flex;flex-direction:column;justify-content:space-between}
	.action-btn{cursor:pointer}
	.empty-data{text-align:center;padding:30px!important;color:rgba(0,0,0,.25)}
	.total-data{padding:15px!important;background:#fafafa;color:#333}
	.goods-money{color:#ff4d4f;}
	.store-view{margin-top:10px}
	.store-view .layui-form-label{width:100px;text-align:center}
	.store-view .layui-input-block{margin-left:100px}
</style>
{/block}
{block name="main"}
<div class="layui-form form">

	<div class="stock-view">

		<div class="store-view">
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label"><span class="required">*</span>出库门店：</label>
					<div class="layui-input-block len-mid">
						<select name="output_store_id" lay-verify="required" lay-filter="store_list" class="len-mid">
							{foreach $store_list as $store_k => $store_v}
							<option value="{$store_v.store_id}" {if $store_k == 0} {php} $default_store_id = $store_v['store_id'];  {/php} selected {/if}>{$store_v.store_name}</option>
							{/foreach}
						</select>
					</div>
				</div>
				<div class="layui-inline">
					<label class="layui-form-label"><span class="required">*</span>入库门店：</label>
					<div class="layui-input-block len-mid">
						<select name="input_store_id" class="len-mid"></select>
					</div>
				</div>
				<div class="layui-inline">
					<label class="layui-form-label"><span class="required">*</span>调拨时间：</label>
					<div class="layui-input-block len-mid">
						<input type="text" name="allot_time" class="layui-input" id="allot_time" placeholder="调拨日期">
					</div>
				</div>
			</div>
		</div>
		<table class="layui-table" lay-size="lg">
			<colgroup>
				<col width="350">
				<col width="120">
				<col width="90">
				<col width="110">
				<col width="110">
				<col width="120">
				<col width="90">
			</colgroup>
			<thead>
				<tr>
					<th>产品名称/规格/编码</th>
					<th>当前库存</th>
					<th>单位</th>
					<th>数量</th>
					<th>成本价</th>
					<th>总金额</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody class="stock-body">
				<tr class="stock-search-line">
					<td class="stock-search-block">
						<input type="text" class="layui-input stock-search" placeholder="请输入产品名称/规格/编码" style="border:none;padding-left:0;"/>
						<div class="stock-autocomplete-list">
							<ul></ul>
						</div>
					</td>
					<td></td>
					<td></td>
					<td></td>
					<td></td>
					<td></td>
					<td></td>
				</tr>
			</tbody>
			<tfoot>
				<tr>
					<td colspan="7" class="total-data">合计: 共<span class="kinds-num">0</span>种，<span class="count-num">0</span>件产品，合计金额：<span class="goods-money">0</span></td>
				</tr>
			</tfoot>
		</table>

		<div class="form-row">
			<button class="layui-btn" lay-submit lay-filter="save">确认调拨</button>
			<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
		</div>
	</div>

</div>

<script type="text/html"  id="stock_goods_info">
	<tr class="stock-tr" data-key='{{ d.sku_id }}'>
		<td>
			<div class="ns-table-title">
				<div class="ns-title-pic" id="goods_img_{{d.sku_id}}">
					<img src="{{ns.img(d.sku_image, 'small')}}" layer-src/>
				</div>
				<div class="ns-title-content table-goods-info">
					<div>
						<a href="javascript:;" class="goods-name" title="{{d.sku_name}}" lay-event="preview">{{d.sku_name}}</a>
					</div>
				</div>
			</div>
			<input type="hidden" class="layui-input" name="goods_sku_id" value="{{ d.goods_sku_id || 0 }}"/>
		</td>
		<!-- 库存 -->
		<td>{{ d.real_stock || 0 }}</td>
		<!-- 单位 -->
		<td>{{ d.unit }}</td>
		<!-- 数量 -->
		<td>
			<input type="number" class="layui-input stock-num" name="goods_num" value="{{ d.goods_num || 0 }}" placeholder="0" onchange="dataChange(this)"/>
		</td>
		<!-- 成本价 -->
		<td>
			<span>{{ d.cost_price || 0 }}</span>
		</td>
		<!-- 成本总价 -->
		<td>
			<span class="total-cost-money">{{ d.goods_money || 0 }}</span>
		</td>
		<td>
			<a class="text-color action-btn" onclick="delTr(this)">删除</a>
		</td>
	</tr>
</script>
{/block}
{block name="script"}
<script>
	var count = 0;
	var stock_data = {};//库存数据  {{'sku_info':{}, 'stock' : 0, 'unit':'','goods_num':0, 'goods_price':0,'goods_money':0}}
	var laytpl,form,laydate;
	var temp_list = {};

	var default_store_id = {$default_store_id ?? 0};

	var store_list = {:json_encode($store_list, true)};

	var scanCode = { lastTime: 0, code: '' };
	function clearBarCode() {
		scanCode = {lastTime: 0, code: ''}
	}

	// 监听扫码枪事件
	$(window).keypress(function (e) {
		if(!checkStore()){
			return false;
		}
		var currCode = e.keyCode || e.which || e.charCode;

		var currTime = new Date().getTime();
		if (scanCode.lastTime > 0) {
			if (currTime - scanCode.lastTime <= 100) {
				scanCode.code += String.fromCharCode(currCode);
			} else if (currTime - scanCode.lastTime > 500) {
				// 输入间隔500毫秒清空
				clearBarCode();
			}
		} else {
			scanCode.code = String.fromCharCode(currCode);
		}
		scanCode.lastTime = currTime;

		if(currCode == 13){
			if (scanCode.code.trim().length > 0) {
				autocomplete(scanCode.code.trim(),function () {
					$(".stock-autocomplete-list").hide();
					$('.stock-autocomplete-list ul li:eq(0)').click();
				});
			} else if (!$(".stock-autocomplete-list").is(':hidden')) {
				$('.stock-autocomplete-list ul li:eq(0)').click();
			}
		}
	});

	layui.use(['form', 'laytpl', 'laydate'], function () {
		form = layui.form,laytpl = layui.laytpl,laydate = layui.laydate;
		var repeat_flag = false;
		form.render();
		laydate.render({
			elem: '#allot_time'
			,type: 'datetime'
			,min: '{$start_time}'
			,value: '{$default_time}'
		});

		setStore();
		fetch({});

		//门店选择
		form.on('select(store_list)', function(data){
			var store_id = data.value;
			if(default_store_id > 0){
				layer.confirm('更改门店，将清除已录入的单报明细，确定吗?\n', {
					title: '操作提示',
					btn: ['是', '否'],
					closeBtn: 0,
					yes: function() {
						default_store_id = store_id;
						reset();
						layer.closeAll();
						setStore();
					},
					btn2: function() {
					}
				});
			}else{
				default_store_id = store_id;
			}

		});

		form.render('select');
		form.on('submit(save)', function(data){

			var field = data.field;
			if(!field.input_store_id){
				layer.msg('请选择入库门店');
				return false;
			}
			var stock_json = [];
			var check_return = true;
			if($('.stock-tr').length <= 0){
				layer.msg('请选择产品');
				return false;
			}

			$('.stock-tr').each(function(){
				var obj = $(this);
				var goods_num = obj.find('input[name=goods_num]').val() || 0;
				var goods_name = obj.find('.goods-name').text() || '';
				var goods_sku_id = obj.find('input[name=goods_sku_id]').val() || 0;
				var goods_price = obj.find('[name=goods_price]').html() || 0.00;

				if(goods_num <= 0){
					check_return = false;
					layer.msg('产品:'+goods_name+'调拨数量不能为空');
					return false;
				}

				stock_json.push({goods_num, goods_price,goods_sku_id});
			});

			if(!check_return) return false;

			if(repeat_flag) return false;

			repeat_flag = true;

			field.goods_sku_list = JSON.stringify(stock_json);
			$.ajax({
				type : 'post',
				dataType: 'JSON',
				url : ns.url("stock://shop/stock/addallocate"),
				async : true,
				data : field,
				success : function(res) {
					if (res.code >= 0) {
						location.href = ns.url("stock://shop/stock/allocate");
					} else {
						repeat_flag = false;
						layer.msg(res.message);
					}
					return false;
				}
			})
		});

	});

	function setStore(){
		var output_store_id = $('[name="output_store_id"]').val();
		let html = '';
		$.each(store_list, function (i,e){
			if(e.store_id != output_store_id){
				html += '<option value="'+e.store_id+'">'+e.store_name+'</option>';
			}
		});

		$('[name="input_store_id"]').html(html);
		form.render();
	}

	function back() {
		location.href = ns.url("stock://shop/stock/allocate")
	}

	function autocomplete(text,callback){
		//根据写入的数据来查询相似的数据
		$.ajax({
			url: ns.url("stock://shop/stock/getskulist"),
			data: {search:text,store_id:default_store_id},
			dataType: 'JSON',
			type: 'POST',
			success: function(res) {
				$('.stock-autocomplete-list ul').html('');
				temp_list = {};
				if(res.data.length > 0){
					$(".stock-autocomplete-list").show();
				}else{
					$(".stock-autocomplete-list").hide();
				}

				$.each(res.data, function(index, value){
					temp_list[value.sku_id] = value;
					$('.stock-autocomplete-list ul').append('<li data-sku_id = "'+value.sku_id+'">'+value.sku_name+'</li>');
				});

				$('.stock-autocomplete-list ul li').hover(function(){
					$(".stock-autocomplete-list ul li").removeClass('stock-li-hover');
					$(this).addClass('stock-li-hover');
				}).click(function(){
					var sku_id = $(this).data('sku_id');
					var item = temp_list[sku_id];
					$(".stock-autocomplete-list").hide();
					$('.stock-search').val('');
					var temp_item = {};

					var temp_one_item = stock_data[sku_id];
					if(ns.checkIsNotNull(temp_one_item)){
						stock_data[sku_id]['goods_num'] += 1;
					}else{
						item.goods_num = 0;
						item.goods_price = 0;
						item.goods_sku_id = sku_id;
						temp_item[sku_id] = item;
					}
					fetch(temp_item);
				});

				if(callback) callback();

			}
		});

	}

	$(function(){
		$(".stock-search").click(function(event){
			if(!checkStore()){
				return false;
			}
			if (!Object.keys(temp_list).length) autocomplete($(this).val());

			if(ns.checkIsNotNull(temp_list)){
				$(".stock-autocomplete-list").show();
			}
			event.stopPropagation();
			return false;
		});

		var timeout = null;
		$("body").on('keyup', '.stock-search', function(e){
			if (e.keyCode != 13) {
				var val = $(this).val();
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function () {
					autocomplete(val);
				}, 800)
			}
		});

		$('body').click(function(){
			$(".stock-autocomplete-list").hide();
		});

	});
	//选择自动补全列表
	function autocompleteSelect(){
		//定位当前选中的sku记录
	}

	//数据渲染（任何来源）
	function fetch(data){
		stock_data = $.extend(stock_data, data);
		//重新渲染
		var template = $("#stock_goods_info").html();
		$('.stock-body tr').not('.stock-search-line').remove();

		if(ns.checkIsNotNull(stock_data)){
			$.each(stock_data, function (index,value){
				value.key = index;
				laytpl(template).render(value, function (html) {
					$('.stock-body').append(html);
					form.render();
				})
			})
		}else{
			$('.stock-body').append('<tr> <td colspan="7" class="empty-data">无数据</td> </tr>');
		}
		form.render();
		syncData();
	}

	function dataChange(obj){
		syncData();
	}

	function syncData(){
		var count_num = 0,goods_money = 0;
		var kinds_data = [];
		$('.stock-tr').each(function(){
			var obj = $(this);
			var key = obj.data('key');
			var goods_sku_id = obj.find('input[name=goods_sku_id]').val() || 0;
			var goods_num = parseFloat(obj.find('input[name=goods_num]').val()) || 0;
			var goods_price = parseFloat(obj.find('[name=goods_price]').html()) || 0;
			if(kinds_data.indexOf(goods_sku_id) == -1){
				kinds_data.push(goods_sku_id)
			}
			//重新采集数据
			stock_data[key].goods_num = goods_num;//库存数量
			stock_data[key].goods_price = goods_price;//库存价格
			count_num += goods_num;
			goods_money += goods_num * goods_price;
			obj.find('.total-cost-money').text(parseFloat(goods_num*goods_price).toFixed(2));
		});
		$(".kinds-num").text(parseInt(kinds_data.length));
		$(".count-num").text(parseFloat(count_num));
		$(".goods-money").text(parseFloat(goods_money).toFixed(2));
	}

	function reset(){
		stock_data = {};
		temp_list = {};
		fetch();
		syncData();
	}

	function checkStore(){
		return true;
	}
	function delTr(obj){
		var parent = $(obj).parents('.stock-tr');
		var key = parent.data('key');//唯一值  (sku_id不承担)
		parent.remove();
		delete stock_data[key];
		syncData();
	}
</script>
{/block}